import json
from .OnlineHandler import OnlineHandler
from elasticsearch import Elasticsearch
from conf.env import elastsearch_url
from ..models import Datasource
from jinjasql import JinjaSql

j = JinjaSql()


class ElastSearchSource:
    def __init__(self):
        self.conn_list = {}

    def connect(self, name, host, port, user, password, database):
        if password:

            es = Elasticsearch(
                ['http://{}:{}/'.format(host, port)],
                http_auth=(user, password)
            )
        else:
            es = Elasticsearch(
                ['http://{}:{}/'.format(host, port)],
            )
        self.conn_list[name] = es

    def testconnect(self, host, port, user, password, database):
        if password:

            es = Elasticsearch(
                ['http://{}:{}/'.format(host, port)],
                http_auth=(user, password)
            )
        else:
            es = Elasticsearch(
                ['http://{}:{}/'.format(host, port)],
            )
        try:
            # 尝试连接 Elasticsearch，并检查是否健康
            if es.ping():
                return True
            else:
                return False, "Connection failed."
        except ConnectionError as e:
            return False, "Connection failed."

    def cursor(self, name):
        if name in self.conn_list.keys():
            return self.conn_list[name]
        return



ElastSearchInit = ElastSearchSource()


class ElastSearchHandel(OnlineHandler):

    def __init__(self, obj, requestdata, id, test):
        self.obj = obj
        self.requestdata = requestdata
        self.userid = id
        self.test = test
        self.query = None
        self.bind_params = None
        self.newQuery = None
        self.curor = None

    def sqlprocess(self):
        request = self.requestdata
        if not self.test:
            namelist = {}
            for i in self.obj['parameter']:
                if self.requestdata.get(i["name"]):
                    if i["typed"] == 'int':
                        namelist.update({i["name"]: int(self.requestdata[i['name']])})
                    elif i["typed"] == 'str':
                        namelist.update({i["name"]: '"' + self.requestdata[i['name']] + '"'})
                    else:
                        namelist.update({i["name"]: self.requestdata[i['name']]})
                elif i["typed"] == 'user':
                    namelist.update({i["name"]: self.userid})
            request = namelist

        query, bind_params = j.prepare_query(self.obj['sql'], request)
        newquery = query % tuple(bind_params)
        self.query = json.loads(newquery)

    def createCursor(self):
        conn = ElastSearchInit.cursor(self.obj['datasource'])
        if conn:
            self.cursor = conn
            return
        obj = Datasource.objects.get(id=self.obj['datasource'])
        ElastSearchInit.connect(obj.id, obj.host, obj.port, obj.user, obj.password, obj.database)
        self.cursor = ElastSearchInit.cursor(self.obj['datasource'])

    def process(self):
        data = self.cursor.search(index=self.requestdata['index'], body=self.query, size=10)
        return data
